Imports System.IO       'For the handy Path.Stuff functions
Imports System.Xml
Imports System.Drawing
Imports System.Drawing.Imaging

Partial Class atomcontrols_controls_ImageLib
    Inherits System.Web.UI.UserControl

    Private _allowedFiles() As String = {".gif", ".jpg"}
    Private _maxSizeKb As Integer = 50
    Private _imageLibPath As String

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'The default path to the image library xml file.
        _imageLibPath = Server.MapPath("~/App_Data/imagelib.xml")

        'Setup the Xml data source.
        XmlImageLib.DataFile = _imageLibPath
        XmlImageLib.EnableViewState = False
        XmlImageLib.EnableCaching = False

    End Sub

    'Public Overrides Sub RenderControl(ByVal writer As System.Web.UI.HtmlTextWriter)
    '    Dim s As String = writer.InnerWriter.ToString
    '    'Dim o As String = "<span id=" & Convert.ToChar(34) & "ImgLib_ImageList" & Convert.ToChar(34) & "><span>"
    '    's = s.Replace(o, "<span id=" & Convert.ToChar(34) & "ImgLib_ImageList" & Convert.ToChar(34) & ">")
    '    's = s.Replace("</span></


    '    s = s.Replace("span", "bum")
    '    Dim sb As New StringBuilder
    '    sb.Append(s)
    '    Dim sr As New StringWriter(sb)

    '    Dim w As New HtmlTextWriter(sr)

    '    ' Dim w As New HtmlTextWriter()

    '    MyBase.RenderControl(w)
    '    'writer.Write(s)
    '    'RenderControl(writer)
    'End Sub
    ''' <summary>
    ''' Handle the uploading of the file.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click

        Dim statusMessage As String = String.Empty
        lblError.Visible = False
        lblSuccess.Visible = False

        'If we have a file, upload that bad boy...
        If FileUpload.HasFile Then

            Try

                With FileUpload

                    'Get the extension of the uploaded file.
                    Dim ext As String = Path.GetExtension(.FileName).ToLower

                    'If we have an allowed file extension.
                    If isExtValid(ext) Then

                        'Make sure the file is less than the maximum allowed size.
                        If (_maxSizeKb * 1024) > .PostedFile.ContentLength Then

                            Dim fullFileName As String = Server.MapPath("~/user/images/" & .FileName)

                            'Save it to the server.
                            .SaveAs(fullFileName)

                            'Save the file to the XML library.
                            Try

                                Dim imgLib As XmlDocument = XmlImageLib.GetXmlDocument()
                                imgLib.Load(_imageLibPath)

                                Dim images As XmlNode = imgLib.DocumentElement

                                Dim img As XmlElement

                                'Try and get an existing node with the same file name if poss.
                                img = imgLib.SelectSingleNode("images/img[@src = '" & .FileName & "']")

                                'If the image doesn't already exist create a new node for it.
                                If img Is Nothing Then
                                    img = imgLib.CreateElement("img")
                                Else
                                    img.RemoveAllAttributes()
                                End If

                                'Load the file in to a bitmap object so we can get the width and height.
                                Dim bmp As New Bitmap(fullFileName)

                                img.SetAttribute("src", .FileName)
                                img.SetAttribute("alt", txtAlt.Text)
                                img.SetAttribute("size", .PostedFile.ContentLength)
                                img.SetAttribute("w", bmp.Height)
                                img.SetAttribute("h", bmp.Width)

                                images.AppendChild(img)
                                imgLib.Save(_imageLibPath)

                                'DONE! It's all good... output our success message.
                                lblSuccess.Visible = True
                                lblSuccess.Text = String.Format(lblSuccess.Text, .FileName)

                                'Rebind the image list.
                                ImageList.DataBind()

                            Catch ex As Exception
                                statusMessage = "Error saving file to image library XML. " & ex.Message
                            End Try

                        Else

                            'File is too big.
                            statusMessage = String.Format("The file size is too large. It must be less than {0} KB.", _maxSizeKb)

                        End If

                    Else
                        'Extension not permitted.
                        statusMessage = "You are not permitted to upload files of that type."
                    End If

                End With

            Catch ex As Exception
                statusMessage = ex.Message
            End Try

        Else
            statusMessage = "Please select a file to upload."
        End If

        'Output the error message if any.
        With lblError

            If Not statusMessage = String.Empty Then
                .Visible = True
                .Text = "<p>" & statusMessage & "</p>"
            End If

        End With

    End Sub

    ''' <summary>
    ''' Determines if we have a valid file extension.
    ''' </summary>
    ''' <param name="ext"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function isExtValid(ByVal ext As String) As Boolean
        Dim isExtAllowed As Boolean = False

        'Find out if the actual file extension matches one of our allowed types.
        For Each ae As String In _allowedFiles
            If ae = ext Then
                isExtAllowed = True
                Exit For
            End If
        Next
        Return isExtAllowed
    End Function

    ''' <summary>
    ''' The full path to the image library xml.
    ''' </summary>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Property ImageLibPath() As String
        Get
            Return _imageLibPath
        End Get
        Set(ByVal value As String)
            _imageLibPath = value
        End Set
    End Property

    ''' <summary>
    ''' Fired by the DeleteCommand event of the datalist.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Protected Sub Delete_Command(ByVal sender As Object, ByVal e As DataListCommandEventArgs)

        'The image name of the selected image.
        Dim fileSrc As String = ImageList.DataKeys(e.Item.ItemIndex)

        Dim imgLib As XmlDocument = XmlImageLib.GetXmlDocument()

        'Get the images node and remove the matching child.
        Dim images As XmlNode = imgLib.DocumentElement
        images.RemoveChild(imgLib.SelectSingleNode("images/img[@src = '" & fileSrc & "']"))

        'Save the library.
        imgLib.Save(_imageLibPath)

    End Sub

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender

        ImageList.DataSource = XmlImageLib
        ImageList.DataBind()

    End Sub

End Class
